package cn.bm.web.controllers.user;

import cn.bm.web.services.UserServices;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.Spark;

import static spark.Spark.*;

public class UserController {
    static Route login = (req, res) -> {
        // 设置 session
        String username = req.queryParams("username");
        String password = req.queryParams("password");
        Boolean loginSuccessful = UserServices.login(username, password);
        System.out.println("logined:" + loginSuccessful);
        if (!loginSuccessful) {
            res.redirect("/login.html");
        } else {
            req.session().attribute("username", username);
            res.redirect("/success.html");
        }
        return "login";
    };

    static Route register = (req, res) -> {
        // 获取用户提交的注册信息
        String username = req.queryParams("username");
        String password = req.queryParams("password");
        String recheckpassword = req.queryParams("recheckpassword");
        boolean registrationSuccessful = UserServices.register(username, password);
        if (registrationSuccessful) {
            // 注册成功，可以进行重定向或者返回成功信息
            res.redirect("/register.html");
            return "Registration successful! You can now log in.";
        } else {
            // 注册失败，可以返回错误信息或者重定向到注册页面并显示错误提示
            res.redirect("/register.html?error=Registration failed.");
            return "Registration failed. Please try again.";
        }
    };

    static Route test = (req, res) -> {
        System.out.println(req.ip());
        if (isUserLoggedIn(req)) {
            return "This is the test page. Only logged in users can access.";
        } else {
            res.redirect("/login.html");
            return "You need to log in to access this page.";
        }
    };

    private static boolean isUserLoggedIn(Request req) {
        String username = req.session().attribute("username");
        return username!= null;
    }

    public static void InitRoutes() {
        System.out.println("init user controller");
        post("/user/login", login);//登录
        get("/user/register", register);
        get("/app/test", test);//登录

        // 添加一个新的所有用户都能访问的路径
        get("/new/public/path", (req, res) -> "This is a new public path.");

        // 添加受限路由，以 /auth 开头的路径需要登录后才能访问
        Route authProtectedRoute = (req, res) -> {
            if (!isUserLoggedIn(req)) {
                res.redirect("/login.html");
                return "You need to log in first.";
            } else {
                return "This is an auth-protected route.";
            }
        };
        get("/auth/somepath", authProtectedRoute);//登录
    }
}